import {messages} from "share/common";
import React from 'react'
import debounce from 'lodash.debounce';
import { Spin, Input, Card, Row, Col, Icon, Popover, Alert, Modal } from 'antd'
const Search = Input.Search;
import defaultExpenseTypeIcon from 'images/expense/default-expense-type.png'
import 'styles/components/template/expense-type-selector.scss'
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
import baseService from 'share/base.service'
import Condition from 'components/condition'
const { If } = Condition;

class ExpenseTypeSelector extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      sourceCategory: [],
      selectedExpenseType: {},
      selectedExpenseTypeArr: [],
      filterCategory: [],
      searchValue: '',
      isShowHistoryExpenseType: true, //是否展示费用选择历史，搜索的时候不展示
      historyExpenseType: [], //费用选择历史记录
      messageInfo: '',
    };
    this.handleSearch = debounce(this.handleSearch, 500);
  }

  componentWillMount(){

  }

  componentDidMount(){
    this.getExpenseType(this.props);
    if (this.props.single) {
      this.setState({selectedExpenseType: this.props.value || {}})
    } else if (!this.props.single) {
      this.setState({selectedExpenseTypeArr: this.props.value || []})
    }
  }

  getExpenseTypeHistory = (props, expenseList) => {
    const { source, param } = props;
    if (source === 'formV2' || source === 'formV3') {
      let queryParam = {
        formOID: param.formOID,
        subsidyType: 99
      };
      if (param.applicantOID) {
        queryParam.applicantOID = param.applicantOID;
      }
      baseService.getExpenseTypesHistoryByFormOID(queryParam).then(res => {
        //校验历史选择的费用是否在费用列表中，不在的情况下要隐藏
        let historyExpenseType = [];
        res.data && res.data.map(history => {
          let isExist = false;
          expenseList && expenseList.map(expense => {
            if (history.expenseTypeOID === expense.expenseTypeOID) {
              isExist = true;
            }
          });
          if (isExist) {
            historyExpenseType.push(history);
          }
        });
        this.setState({
          historyExpenseType
        });
      });
    }
  };

  getSourceCategory = () => {
    const { source, param } = this.props;
    let setOfBooksId = null;
    if (source === 'formV2' || source === 'form' || source === 'formV3' || source === 'custom') {
      setOfBooksId = param.setOfBooksId;
    }
    if (this.state.sourceCategory.length === 0)
      return baseService.getExpenseTypeCategory(setOfBooksId).then(res => {
        this.setState({sourceCategory: res.data ? res.data : [], filterCategory: res.data ? res.data : []});
        return res.data ? res.data : [];
      });
    else
      return new Promise((resolve) => resolve(this.state.sourceCategory));
  };

  getExpenseType = (props) => {
    this.setState({ loading: true });
    let { source, param, filter, receiptList, showMessageInfo } = props;
    let listKey;
    this.getSourceCategory().then(sourceCategory => {
      let request;
      switch(source){
        case 'company':
          request = baseService.getExpenseTypeByCompanyOID;
          break;
        case 'form':
          request = baseService.getExpenseTypesByFormOID;
          listKey = 'expenseTypes';
          break;
        case 'formV2':
          request = baseService.getExpenseTypesByFormOIDV2;
          listKey = 'expenseTypes';
          break;
        case 'user':
          request = baseService.getExpenseTypeByUserOID;
          break;
        case 'formV3':
        case 'custom':
          request = baseService.getExpenseTypesByCustomParams;
          if (receiptList && receiptList[0]) { // 发票筛选费用
            param.receiptList = receiptList;
          }
          listKey = 'rows';
          break;
      }
      request && request(param).then(res => {
        let target = res.data;
        if(listKey)
          target = res.data[listKey];
        target = target.filter(filter);
        this.getExpenseTypeHistory(this.props, JSON.parse(JSON.stringify(target)));
        if (source !== 'formV2' && source !== 'formV3')
          target = target.filter(expenseType => expenseType.isAbleToCreatedManually);
        if (source === 'formV3') {
          target = target.filter(t => t.subsidyType !== 1);
        }
        target.map(expenseType => {
          if (expenseType.expenseTypeCategoryOID) {
            sourceCategory.map(item => {
              if(item.expenseTypeCategoryOID === expenseType.expenseTypeCategoryOID){
                if(!item.expenseType)
                  item.expenseType = [];
                item.expenseType.push(expenseType);
                return item;
              }
            })
          } else { //费用类型的expenseTypeCategoryOID为null时, add by mengsha.wang@huilianyi.com
            let nullCategoryItem;
            let nullCategoryOIDExist = false;
            sourceCategory.map(item => {
              if (item.expenseTypeCategoryOID === '0000-0000-0000-0000-0000') {
                nullCategoryItem = item;
                nullCategoryOIDExist = true;
                item.expenseType.push(expenseType);
                return item;
              }
            });
            if (!nullCategoryOIDExist) {
              nullCategoryItem = {
                expenseTypeCategoryOID: '0000-0000-0000-0000-0000',
                name: messages('common.other'),
                expenseType: [expenseType]
              };
              sourceCategory.push(nullCategoryItem)
            }
          }
        });
        this.setState({ sourceCategory, loading: false, messageInfo: showMessageInfo ? res.data.message : '' });
      })
    })
  };

  componentWillReceiveProps(nextProps){
    let nextExpenseType = nextProps.value;
    if (nextProps.single && nextProps.source !== 'formV2' && nextProps.source !== 'formV3' && nextExpenseType && nextExpenseType.id && nextExpenseType.id !== this.state.selectedExpenseType.id) {
      this.setState({selectedExpenseType: nextExpenseType})
    } else if (this.checkChange(nextProps, nextExpenseType)) {
      this.setState({selectedExpenseType: nextExpenseType ? nextExpenseType : {}});
    } else if (!nextProps.single && nextExpenseType && nextExpenseType.length !== this.state.selectedExpenseTypeArr.length) {
      this.setState({selectedExpenseTypeArr: nextExpenseType})
    }
  }

  checkChange = (nextProps, nextExpenseType) => {
    let isChange = false;
    if (nextProps.single && (nextProps.source === 'formV2' || nextProps.source === 'formV3')) {
      if (nextExpenseType && nextExpenseType.expenseTypeOID && nextExpenseType.expenseTypeOID !== this.state.selectedExpenseType.expenseTypeOID) {
        isChange = true;
      }
      if (!nextExpenseType || !nextExpenseType.expenseTypeOID) {
        isChange = true;
      }
    }
    return isChange;
  };

  handleSearch = (value) => {
    this.setState({searchValue: value});
    this.getSourceCategory().then(sourceCategory => {
      if(value === '')
        this.setState({ filterCategory: sourceCategory, isShowHistoryExpenseType: true });
      else {
        let result = [];
        sourceCategory.map((category, index) => {
          result.push(Object.assign({}, category));
          result[index].expenseType = [];
          if (category.name.toLowerCase().indexOf(value.toLowerCase()) > -1) {
            if(category.expenseType){
              category.expenseType.map(expenseType => {
                result[index].expenseType.push(expenseType)
              })
            }
          } else {
            if(category.expenseType){
              category.expenseType.map(expenseType => {
                if(expenseType.name.toLowerCase().indexOf(value.toLowerCase()) > -1){
                  result[index].expenseType.push(expenseType)
                }
              })
            }
          }
        });
        this.setState({ filterCategory: result, isShowHistoryExpenseType: false });
      }
    })
  };

  handleSelect = (expenseType) => {
    if (this.props.single) {
      this.setState({
        selectedExpenseType: expenseType.expenseTypeOID === this.state.selectedExpenseType.expenseTypeOID ? {}  : expenseType
      }, () => {
        this.props.onSelect(this.state.selectedExpenseType);
      })
    } else {
      let selectedExpenseTypeArr = this.state.selectedExpenseTypeArr;
      let expenseIndex = -1;
      selectedExpenseTypeArr.map((item, index) => {
        item.expenseTypeOID === expenseType.expenseTypeOID && (expenseIndex = index)
      });
      expenseIndex !== -1 ? selectedExpenseTypeArr.splice(expenseIndex, 1) : selectedExpenseTypeArr.push(expenseType);
      this.setState({ selectedExpenseTypeArr }, () => {
        this.props.onSelect(this.state.selectedExpenseTypeArr)
      })
    }
  };

  renderMessageInfo = () => {
    const { messageInfo } = this.state;
    let showMore = () => (
      Modal.info({
        title: messages('components.key1047')/*隐藏费用类型*/,
        content: messageInfo
      })
    );
    return (
      <If value={messageInfo}>
        <Alert
          type="info"
          message={(
            <Row>
              <Col span={22}><Ellipsis lines={1}>{messageInfo}</Ellipsis></Col>
              <Col span={2} style={{textAlign: 'right'}}><a onClick={showMore}>{messages('common.more')/*更多*/}</a></Col>
            </Row>
          )}
          showIcon
          style={{marginTop: 10}}
        />
      </If>
    )
  };

  renderPopoverContent = (expenseType) => (
    <div className="detail-popover-content">
      <div className="detail-name">{expenseType.name}</div>
      <div className="detail-instruction">{expenseType.instructions}</div>
    </div>
  );

  render() {
    const { loading, filterCategory, selectedExpenseType, selectedExpenseTypeArr, isShowHistoryExpenseType, historyExpenseType, searchValue } = this.state;
    const {recommendExpenseTypeList} = this.props;
    let recommendExpenseTypeListFilter = recommendExpenseTypeList && recommendExpenseTypeList.length > 0 ? recommendExpenseTypeList.filter(item =>
      item.recommendType === 'R' && ~item.name.toLowerCase().indexOf(searchValue.toLowerCase())
    ) : [];
    let resultLength = 0;
    let typeLength = filterCategory.length - 1;
    let getExpenseTypeRender = (expenseType,className) => {
      return <Col span={8} key={expenseType.expenseTypeOID} onClick={() => {
        this.handleSelect(expenseType)
      }}>
        <Card className={`expense-card ${className}`}>
          <Icon type="check-circle-o" className="selected-icon"/>
          <img src={expenseType.iconURL || defaultExpenseTypeIcon} onError={e => e.target.src = defaultExpenseTypeIcon}/>
          <Popover
            getPopupContainer={() => document.getElementsByClassName('expense-type-selector')[0]}
            content={this.renderPopoverContent(expenseType)}
          >
            <div className="expense-name">{expenseType.name}</div>
          </Popover>
        </Card>
      </Col>
    }
    return (
      <div className="expense-type-selector">
        <Spin spinning={loading}>
          <Search
            onChange={(value) => {
              this.handleSearch(value.target.value)
            }}
            placeholder={messages('components.key445'/*搜索费用类型*/)}
          />
          {this.renderMessageInfo()}
          {!searchValue && recommendExpenseTypeListFilter && recommendExpenseTypeListFilter.length > 0 && (
            <div className="category-area">
              <div className="category-name">{messages('common.select.recommend')/*系统推荐*/}</div>
              <Row gutter={10}>
                {recommendExpenseTypeListFilter.map(expenseType => {
                  let className = '';
                  if (this.props.single) {
                    expenseType.expenseTypeOID === selectedExpenseType.expenseTypeOID && (className = 'selected')
                  } else {
                    selectedExpenseTypeArr.map(expenseTypeItem => {
                      expenseTypeItem.expenseTypeOID === expenseType.expenseTypeOID && (className = 'selected')
                    })
                  }
                  return (
                    getExpenseTypeRender(expenseType,className)
                  )
                })}
              </Row>
            </div>
          )}
          {isShowHistoryExpenseType && historyExpenseType.length > 0 && (
            <div className="category-area">
              <div className="category-name">{messages('common.select.history')/*历史选择*/}</div>
              <Row gutter={10}>
                {historyExpenseType.map(expenseType => {
                  let className = '';
                  if (this.props.single) {
                    expenseType.expenseTypeOID === selectedExpenseType.expenseTypeOID && (className = 'selected')
                  } else {
                    selectedExpenseTypeArr.map(expenseTypeItem => {
                      expenseTypeItem.expenseTypeOID === expenseType.expenseTypeOID && (className = 'selected')
                    })
                  }
                  return (
                    getExpenseTypeRender(expenseType,className)
                  )
                })}
              </Row>
            </div>
          )}
          {filterCategory.length > 0 ? filterCategory.map((expenseTypeCategory, index) => {
            expenseTypeCategory.expenseType && (resultLength += expenseTypeCategory.expenseType.length);
            if(index === typeLength && resultLength === 0){
              return <div className="search-no-expense" key={index}>{messages('components.key446'/*暂无费用类型*/)}</div>
            }
            return (
              expenseTypeCategory.expenseType && expenseTypeCategory.expenseType.length > 0 ? (
                <div className="category-area" key={expenseTypeCategory.expenseTypeCategoryOID}>
                  <div className="category-name">{expenseTypeCategory.name}</div>
                  <Row gutter={10}>
                    {expenseTypeCategory.expenseType.map(expenseType => {
                      let className = '';
                      if (this.props.single) {
                        expenseType.expenseTypeOID === selectedExpenseType.expenseTypeOID && (className = 'selected')
                      } else {
                        selectedExpenseTypeArr.map(expenseTypeItem => {
                          expenseTypeItem.expenseTypeOID === expenseType.expenseTypeOID && (className = 'selected')
                        })
                      }
                      return (
                        getExpenseTypeRender(expenseType,className)
                      )
                    })}
                  </Row>
                </div>
              ) : null
            )
          }) : <div className="no-expense-type">{messages('components.key446'/*暂无费用类型*/)}</div>}
        </Spin>
      </div>
    )
  }
}

ExpenseTypeSelector.propTypes = {
  onSelect: React.PropTypes.func.isRequired,
  source: React.PropTypes.string,
  param: React.PropTypes.any,
  value: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]),  //single为false时，需要传入数组
  single: React.PropTypes.bool, //是否为单选 add by mengsha.wang@huilianyi.com
  recommendExpenseTypeList: React.PropTypes.array, //系统推荐list
  filter: React.PropTypes.func,
  showMessageInfo: React.PropTypes.bool, //是否需要显示message信息
};

ExpenseTypeSelector.defaultProps = {
  single: true,
  recommendExpenseTypeList: [],
  filter: () => true
};

export default ExpenseTypeSelector;
